package com.tcu.order.controller;

import com.tcu.exception.SmartException;
import com.tcu.order.entity.OrderItem;
import com.tcu.order.service.IOrderItemService;
import com.tcu.result.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orderItem")
public class OrderItemController {
    private IOrderItemService itemService;

    @Autowired
    public void setItemService(IOrderItemService itemService) {
        this.itemService = itemService;
    }

    @PostMapping("add")
    public R add(@RequestBody OrderItem orderItem){
        if(orderItem.getId()!=null){
            throw new SmartException(20001,"id不为空，无法保存");
        }
        if(orderItem.getServeTypeId()==null){
            throw new SmartException(20001,"没有填写服务类型");
        }
        if(orderItem.getOrderId()==null){
            throw new SmartException(20001,"该订单项，无指定的 订单id");
        }
        boolean b = itemService.save(orderItem);
        return b ? R.success().data("itemId",orderItem.getId()) : R.error();

    }

    @DeleteMapping("delete/{id}")
    public R delete(@PathVariable String id){
        boolean b = itemService.removeById(id);
        return b ? R.success() : R.error();
    }

    @PostMapping("deleteBatch")
    public R deleteBatch(@RequestBody List<String> ids){
        boolean b = itemService.removeByIds(ids);
        return b ? R.success() : R.error();
    }

    @PostMapping("update")
    public R update(@RequestBody OrderItem orderItem){
        if (orderItem.getId()==null) {
            throw new SmartException(20001,"id为null，无法更新");
        }
        boolean b = itemService.updateById(orderItem);
        return b ? R.success() : R.error();
    }

    @GetMapping("getItemsByOrderId/{orderId}")
    public R getItemsByOrderId(@PathVariable String orderId){
        List<OrderItem> allItemByOid = itemService.getAllItemByOid(orderId);
        return R.success().data("list", allItemByOid);
    }

    @DeleteMapping("deleteItemsByOrderId/{orderId}")
    public R deleteItemsByOrderId(@PathVariable String orderId){
        Integer integer = itemService.deleteItemByOid(orderId);
        return integer != 0 ? R.success() : R.error();
    }
    @GetMapping("getItemsByType/{orderId}/{typeId}")
    public R getItemsByType(@PathVariable String orderId,@PathVariable String typeId){
        List<OrderItem> itemByType = itemService.getItemByType(orderId, typeId);
        return R.success().data("items", itemByType);
    }
}
